package com.github.hwangrq.myrpc.consumer.client;

import com.github.hwangrq.myrpc.api.zk.ZkConstant;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Component
public class CronServer {

    @Scheduled(fixedRate = 5000)
    public void scheduledTask() {
        ZkClient zkClient = new ZkClient(ZkConstant.DEFAULT_SERVER);
        List<String> children = zkClient.getChildren(ZkConstant.NAMESPACE);
        for (String child : children) {
            String ip = child.split(":")[0];
            String port = child.split(":")[1];
            Bootstrap bootstrap = new Bootstrap();
            //2)创建连接池对象
            EventLoopGroup group = new NioEventLoopGroup();
            //3)创建客户端的引导对象
            //4)配置启动引导对象
            bootstrap.group(group)
                    //设置通道为NIO
                    .channel(NioSocketChannel.class)
                    //设置请求协议为TCP
                    .option(ChannelOption.TCP_NODELAY, true)
                    //监听channel 并初始化
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取ChannelPipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //设置编码
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                        }
                    });

            long start = System.currentTimeMillis();
            bootstrap.connect(ip, Integer.parseInt(port));
            long end = System.currentTimeMillis();
            long time = (end - start);

            //如果耗时超过5秒，则认为该节点失效，从ZK节点上删除
            String path = ZkConstant.NAMESPACE + "/" + ip + ":" + port;
            if (time > 5000) {
                zkClient.delete(path);
                System.out.println("【定时任务delete】path:{}, data:{}, 执行时间：{}"+path+":"+"{}path:"+time+"{dater}:"+LocalDateTime.now());

            } else {
                //将该节点数据修改为耗时时间
                zkClient.writeData(path, String.valueOf(time));
                System.out.println("【定时任务writeData】path:{}, data:{}, 执行时间：{}"+path+":"+"{}path:"+time+"{dater}:"+LocalDateTime.now());
            }
        }
    }
}
